function handleHzfw() {
    layer.open({
        type: 1,
        area: ['500px', '300px'],
        btn: ['确定', '取消'], //按钮,
        content: '<div class="w-right-div"><label style="vertical-align: top;">汇总范围：</label><textarea class="w-jsl-textarea"></textarea></div>'
    });
}

function setSummaryLevel() {
    layer.open({
        offset: 'r',
        shade: 0,
        anim: 4,
        title: '汇总级别',
        // content: levelList
    });
}

function selectReportOption(_this) {
    $(_this).addClass('w-zb-options-select').siblings().removeClass('w-zb-options-select');
    $(_this).attr('id', 'zb_select_1').siblings().removeAttr('id', '');
    $("#xspc").val($(_this).attr('value') + '(' + $(_this).attr('code') + ')')
}

var zbNumKey = '';
var options = "";
var ziDuanOptions = "";
var column = "";

function changeZbVal(_this) {
    var selectedOption = event.target.selectedOptions[0]
    zbNumKey = selectedOption.getAttribute('value')
    options = ''
    ziDuanOptions = ''
    $("#zb_select_option").empty()
    $("#zb_select_2").empty()
    renderZbListHtml(zbNumKey)
    $("#zb_select_option").append(options)
    $("#zb_select_2").append(ziDuanOptions)
}

function renderZbListHtml(val) {
    column = columnList[val]
    if (column) {
        var zblist = column.zblist
        options = '';
        for (var i = 0; i < zblist.length; i++) {
            var className = i % 2 == 0 ? "w-ss" : "w-qs"
            if (i == 0) {
                className += ' w-zb-options-select'
            }
            options += '<div class="w-zb-options ' + className + '" id="zb_select_1" rnum="' + zblist[i].rnum + '"value="' + zblist[i].NAME + '" code="' + zblist[i].ZBDM + '" onclick="selectReportOption(this)">' + zblist[i].NAME + '</div>'
        }
        var zbOptions = column.collist;
        ziDuanOptions = '';
        for (var j = 0; j < zbOptions.length; j++) {
            ziDuanOptions += '<option value="' + zbOptions[j].COLNAME + '" code="' + zbOptions[j].COLBM + '" colType="' + zbOptions[j].COLTYPE + '">' + zbOptions[j].COLNAME + '</option>'
        }
    }
}

function showShowAddHtml(treeNode, ctype) {

    function getSubNodes(nodes) {
        if (nodes == 'undefined') {
            return false;
        }
        var arr = []
        for (var i = 0; i < nodes.length; i++) {
            var node = nodes[i]
            arr.push(node.name)
            if (node.children && node.children.length > 0) {
                arr = arr.concat(getSubNodes(node.children))
            }
        }
        return arr;
    }
    var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
    var nodes = treeObj.getNodes();
    var nameArr = getSubNodes(nodes[0].children)

    var html = '<div class="w-head"><span class="w-select" onclick="changeTab(0, this)">计算列</span><span onclick="changeTab(1, this)">指标</span></div>'

    var selectOptions = ""
    for (var i = 0; i < num.length; i++) {
        selectOptions += '<option value="' + num[i] + '">' + num[i] + '</option>'
    }

    renderZbListHtml(num[0])

    var startTimeOptions = ""
    var endTimeOptions = ""
    var value = ['当前报告期', '上期', '去年同期']
    for (var i = 0; i < value.length; i++) {
        startTimeOptions += '<option value="' + value[i] + '">' + value[i] + '</option>'
        endTimeOptions += '<option value="' + value[i] + '">' + value[i] + '</option>'
    }
    var showName = ""
    var ifShowOptions = ''

    var choosedItem = '';
    for (var i = 0; i < nameArr.length; i++) {
        choosedItem += '<div class="w-zb-options" onclick="getOptionsCode(' + (i + 1) + ')">' + (i + 1) + '.' + nameArr[i] + '</div>'
    }

    var nameVal = '';
    var tjfwVal = '';
    var express = '';
    if (ctype == 'edit') {
        nameVal = treeNode.name;
        if (treeNode.hasOwnProperty('tjfw')) {
            tjfwVal = treeNode.tjfw;
        }
        if (type == 'update' && treeNode.hasOwnProperty('rangeCondition')) {
            tjfwVal = treeNode.rangeCondition
        }
        if (treeNode.hasOwnProperty('express')) {
            express = treeNode.express;
        }
        if (type == 'update' && treeNode.hasOwnProperty('columnAdded')) {
            express = treeNode.columnAdded;
        }
    }

    var operatorHtml = `<div class="panel panel-default">
                <div class="panel-heading">运算符</div>
                <div class="panel-body">
                    <div class="btn-toolbar" id="operator_tool">
                        <div class="btn-group">
                        <button class="btn" onclick="getOperatorToolVal('+')">+</button>
                        <button class="btn" onclick="getOperatorToolVal('-')">-</button>
                        <button class="btn" onclick="getOperatorToolVal('*')">*</button>
                        <button class="btn" onclick="getOperatorToolVal('/')">/</button>
                        </div>
                        <div class="btn-group">
                        <button class="btn" onclick="getOperatorToolVal('(')">(</button>
                        <button class="btn" onclick="getOperatorToolVal(')')">)</button>
                        <button class="btn" onclick="getOperatorToolVal('%')">%</button>
                        <button class="btn" onclick="getOperatorToolVal('=')">=</button>
                        </div>
                    </div>
                </div>
            </div>`

    html += '<div class="w-model-content">'

    html += '<div class="w-model-box clearfix">'
    html += '    <div class="w-left">'
    html += '        <div class="w-left-options">' + choosedItem + '</div>'
    html += '    </div>'
    html += '    <div class="w-right-box"><div class="w-right">'
    html += '        <div class="w-right-div"><label>显示名称：</label><input class="w-jsl-input" id="ggxspc" type="text" value="' + nameVal + '"/></div>'
    html += '        <div class="w-right-div"><label>统计范围：</label><input class="w-jsl-input" id="ggtjfw" type="text" value="' + tjfwVal + '" /></div>'
    html += '        <div class="w-right-div"><label>是否显示：</label><select id="ggifshow" class="w-jsl-select"><option value="Y">显示</option><option value="N">不显示</option></select></div>'
    html += '        <div class="w-right-div"><label style="vertical-align: top;">计算表达式：</label><textarea id="ggjsbdas" class="w-jsl-textarea">' + express + '</textarea></div>'
    html += '    </div>' + operatorHtml + '</div>'
    html += '</div>'

    html += '<div class="w-model-box clearfix" style="display: none;">'
    html += '    <div class="w-left">'
    html += '        <div class="w-title"><label>可选报表：</label><select onchange="changeZbVal(this)">' + selectOptions + '</select></div>'
    html += '        <div class="w-left-options" id="zb_select_option">' + options + '</div>'
    html += '    </div>'
    html += '    <div class="w-right">'
    html += '        <div class="w-right-div"><label>字段：</label><select class="w-jsl-select" id="zb_select_2">' + ziDuanOptions + '</select></div>'
    html += '        <div class="w-right-div"><label>开始时间：</label><select class="startTime w-jsl-select" id="zb_select_3">' + startTimeOptions + '</select></div>'
    html += '        <div class="w-right-div"><label>结束时间：</label><select class="endTime w-jsl-select" id="zb_select_4">' + endTimeOptions + '</select></div>'
    html += '        <div class="w-right-div"><label>显示名称：</label><input class="w-jsl-input" id="xspc" value="' + nameVal + '" type="text"></div>'
    html += '        <div class="w-right-div"><label>是否显示：</label><select class="w-jsl-select" id="zb_select_5"><option value="Y">显示</option><option value="N">不显示</option></select></div>'
    html += '    </div>'
    html += '</div>'

    html += '</div>'

    layer.open({
        type: 1,
        title: false,
        closeBtn: 0,
        area: ['800px', '600px'],
        shadeClose: true,
        skin: 'yourclass',
        btn: ['确定', '取消'], //按钮,
        content: html,
        success: function() {
            var numbers = $("#ggifshow").find("option");
            for (var j = 1; j < numbers.length; j++) {
                if ($(numbers[j]).val() == treeNode.display) {
                    $(numbers[j]).attr("selected", "selected");
                }
            }
        },
        yes: function(index) {
            // if(!$('#ggxspc').val()) {
            //     alert('请填写指标名称！')
            //     return;
            // }
            if (ctype == 'edit') {
                var isZhibiao = $('.w-select')[0].innerHTML == "指标"
                layer.close(index);
                getZBResult(treeNode, true, isZhibiao, type)
                totalSaveBtnEnable = true
            }
            if (ctype == 'add') {
                var isZhibiao = $('.w-select')[0].innerHTML == "指标"
                layer.close(index);
                getZBResult(treeNode, false, isZhibiao, type)
                totalSaveBtnEnable = true
            }
        }
    });
}

function getOptionsCode(code) {
    var codeVal = '${' + code + '}';
    var txtAreaVal = $("#ggjsbdas").val();
    $("#ggjsbdas").val(txtAreaVal + codeVal);
}

function getOperatorToolVal(val) {
    var txtAreaVal = $("#ggjsbdas").val();
    $("#ggjsbdas").val(txtAreaVal + val);
}

function changeTab(index, _this) {
    $(_this).addClass('w-select').siblings().removeClass('w-select')
    $(".w-model-box").eq(index).show().siblings().hide()
}

var URL = 'http://192.168.0.175:8081/trueLWZB/commonReportController/';

function getJSONData(url, callback) {
    $.ajax({
        type: "GET",
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        dataType: "jsonp",
        url: url,
        jsonp: 'callback',
        success: function(json) {
            callback(json)
        },
        timeout: 90 * 1000,
        error: function(XMLHttpRequest, textStatus, errorThrown) {}
    });
}

function postJSONData(url, data, callback) {
    $.ajax({
        type: "POST",
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        url: url,
        data: data,
        success: function(json) {
            callback(json)
        },
        dataType: 'jsonp'
    })
}

function GetRequest() {
    var url = location.search; //获取url中"?"符后的字串 
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}

function trueWayCopyObj(item) {
    if (item instanceof Array) {
        var arr = []
        for (var key in item) {
            arr[key] = trueWayCopyObj(item[key])
        }
        return arr
    } else if (item instanceof Object) {
        var obj = {}
        for (var key in item) {
            obj[key] = trueWayCopyObj(item[key])
        }
        return obj
    } else {
        return item
    }
}

var blNameArrays = new Array(),
    zlNameArrays = new Array(),
    zNodes = [],
    flag = 0,
    saveNodes = [];
var originBlNameArrays = [];
var originZlNameArrays = [];

var columnList = []
var rowList = {}

var calcResult = null;
var treeBlDate = []

var totalSaveBtnEnable = false;

var layer, laydate;
var url = GetRequest(),
    values = 0,
    num = url.rnum;
var tplId = GetRequest().tplId;
var type = GetRequest().type;
var tplName = '';


function uploadNodes() {

    if (totalSaveBtnEnable || !totalSaveBtnEnable) {
        totalSaveBtnEnable = false

        var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
        if (!treeObj) {
            createTree()
            treeObj = $.fn.zTree.getZTreeObj("treeDemo");
        }
        var nodes = treeObj.getNodes();
        var pxh = 0
        var rnum = []
        var blArr = []
        var zlArr = []
        if (nodes.length > 0) {
            for (key in nodes) {
                if (nodes.hasOwnProperty(0) && nodes.hasOwnProperty(1)) {
                    blArr = getBlArr(nodes[0].children || [])
                    zlArr = getZlArr(nodes[1].children || [])
                } else {
                    return;
                }
            }
            if (blArr.length == 0 || zlArr.length == 0) {
                return;
            }
            var zbVal = [];
            var fzVal = [];
            for (var i = 0; i < blArr.length; i++) {
                zbVal.push(blArr[i].name)
            }
            for (var i = 0; i < zlArr.length; i++) {
                fzVal.push(zlArr[i].groupName)
            }
            tplName ? tplName : '';
        } else {
            alert('请选择需要保存的指标');
        }
        var saveHtml = '<div>' +
            '<div class="s-model-name">' +
            '<label for="moduleName">模板名称：</label>' +
            '<input id="moduleName" class="w-jsl-input" value="' + tplName + '" />' +
            '</div>' +
            '<div class="s-table1-box">' +
            '<table class="s-table1">' +
            '<tr><td class="bg-gre">选择的指标为：</td><td><input class="s-input" type="text" value="' + zbVal.join(',') + '" /></td></tr>' +
            '<tr><td class="bg-gre">选择的分组为：</td><td><input class="s-input" type="text" value="' + fzVal.join(',') + '" /></td></tr>' +
            '<tr><td class="bg-gre">汇总级别：</td><td><input class="s-input" type="text" /></td></tr>' +
            '<tr><td class="bg-gre">时间范围为：</td><td><input class="s-input" type="text" /></td></tr>' +
            '<tr><td class="bg-gre">设置条件为：</td><td><input class="s-input" type="text" /></td></tr>' +
            '<tr><td class="bg-gre">表样显示：</td><td><input class="s-input" type="text" /></td></tr>' +
            '</table>' +
            '</div>' +
            '<div class="main-box">' +
            '<h1 class="h-title">临时汇总</h1>' +
            '<div class="mt20" style="overflow:hidden;">' +
            '<div class="fl">' +
            '<span>汇总机构名称：</span>' +
            '<span class="color-black">南通市统计局</span>' +
            '</div>' +
            '<div class="fr">' +
            '<span>报告期：</span>' +
            '<span class="color-black">2017年10月</span>' +
            '</div>' +
            '</div>' +
            '<table cellpadding="0" cellspacing="0" class="JS_table tj-right-table main-table table-demo" id="save_demo"><thead><tr><td>项目</td><td>代码</td></tr></thead><tbody><tr><td>总计</td></tr></tbody></table>' +
            '<div class="mt5" style="overflow:hidden;">' +
            '<div class="fl">' +
            '<span>操作人：</span>' +
            '<span class="color-black">测试</span>' +
            '</div>' +
            '<div class="fr">' +
            '<span>汇总时间：</span>' +
            '<span class="color-black">2017年11月27日</span>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>'
        layer.open({
            area: ['800px', '500px'],
            title: '保存模板',
            content: saveHtml,
            btn: ['保存'], //按钮,
            success: function(layero, index) {
                var container = document.getElementById('save_demo')
                if (typeof blNameArrays === 'object' && Array.isArray(blNameArrays)) {
                    if (typeof zlNameArrays === 'object' && Array.isArray(zlNameArrays)) {
                        generateTable([getTreeJson(blNameArrays.slice(1), 1), getTreeJson(zlNameArrays.slice(1), 1)], container)
                    } else {
                        generateTable([getTreeJson(blNameArrays.slice(1), 1), getTreeJson(zlNameArrays.children, 1)], container)
                    }
                } else {
                    if (typeof zlNameArrays === 'object' && Array.isArray(zlNameArrays)) {
                        generateTable([getTreeJson(blNameArrays.children, 1), getTreeJson(zlNameArrays.slice(1), 1)], container)
                    } else {
                        generateTable([getTreeJson(blNameArrays.children, 1), getTreeJson(zlNameArrays.children, 1)], container)
                    }
                }
            },
            yes: function(index) {
                var tempRnum = rnum.join(',')
                if (tempRnum[tempRnum.length - 1] == "&") {
                    tempRnum = tempRnum.substr(0, tempRnum.length - 1)
                }
                var name = document.getElementById('moduleName').value
                if (name.length > 0) {
                    var params = null;
                    if (type == 'update') {
                        params = {
                            data: JSON.stringify({
                                report: {
                                    rnum: tempRnum,
                                    title: name,
                                    isTotal: 'Y'
                                },
                                row: zlArr, //,/zlArr,
                                column: blArr //blArr
                            }),
                            id: tplId
                        }
                    } else {
                        params = {
                            data: JSON.stringify({
                                report: {
                                    rnum: tempRnum,
                                    title: name,
                                    isTotal: 'Y'
                                },
                                row: zlArr, //,/zlArr,
                                column: blArr //blArr
                            })
                        }
                    }
                    postJSONData(URL + 'saveOrUpdateGroupReportData.do', params, function(json) {
                        if (!json.success) {
                            alert(json.prompt)
                        }
                    })
                    layer.close(index);
                } else {
                    alert('名字不能为空！')
                }
            },
            btn2: function() {}
        });
    }

    function getBlArr(arr) {
        var timeArr = ['${CURYEAR}${CURMONTH}', '${CURYEAR}${CURMONTH-1}', '${CURYEAR-1}${CURMONTH}']
        var result = []
        for (var i = 0; i < arr.length; i++) {
            var obj = {
                "name": arr[i].name,
                "display": arr[i].display,
                "pxh": pxh,
                "zbId": arr[i].zbId,
                "zb": arr[i].indexDm ? arr[i].indexDm : '',
                "id": arr[i].zbId
            }
            if (!arr[i].children) {
                //obj["zb"] = arr[i].indexDm ? arr[i].indexDm : ''
                obj["rangeCondition"] = arr[i].tjfw ? arr[i].tjfw : '';
                if (arr[i].hasOwnProperty('express')) {
                    obj["columnType"] = 'EXPRESS'
                    obj["starttime"] = "${CURYEAR-1}${CURMONTH}"
                    obj["endtime"] = "${CURYEAR-1}${CURMONTH}"
                    obj["columnAdded"] = arr[i].columnAdded ? arr[i].columnAdded : arr[i].express
                    obj["columnName"] = arr[i].rnum + '.' + arr[i].indexColumn
                } else {
                    obj["columnType"] = arr[i].columnType ? arr[i].columnType : 'SUM'
                    obj["starttime"] = arr[i].starttime ? arr[i].starttime : timeArr[arr[i].starttime]
                    obj["endtime"] = arr[i].endtime ? arr[i].endtime : timeArr[arr[i].endtime]
                    obj["columnAdded"] = arr[i].columnAdded ? arr[i].columnAdded : arr[i].express
                    obj["columnName"] = arr[i].rnum + '.' + arr[i].indexColumn
                }
            } else {
                obj.children = getBlArr(arr[i].children)
            }
            pxh++;
            if (rnum.indexOf(arr[i].rnum) < 0) {
                rnum.push(arr[i].rnum)
            }
            result.push(obj)
        }
        return result
    }

    function getZlArr(arr) {
        var result = [];
        for (var i = 0; i < arr.length; i++) {
            var obj = {
                'groupId': arr[i].groupId,
                'pxh': pxh,
                'groupName': arr[i].name,
                'groupType': arr[i].groupType,
                'groupColumn': arr[i].groupColumn,
                'groupAdded': arr[i].cs,
            }
            pxh++
            if (arr[i].children) {
                obj.children = getZlArr(arr[i].children)
            }
            result.push(obj)
        }
        return result
    }
}
$(document).ready(function() {
    if (num) {
        num = num.split(',');
    } else {
        num = ['B203'];
    }

    if (type == 'update' && tplId) {
        getJSONData(URL + 'getGroupReportJsonData.do?id=' + tplId, function(data) {
            if (data.success) {
                tplName = data.data.report.title;
                getSupportStatisticsColumnList(data.data, type);
                getSupportGroupList(data.data, type);
            }
        })
    } else {
        getSupportStatisticsColumnList();
        getSupportGroupList();
    }

    function getSupportStatisticsColumnList(tplData, type) {
        for (var i = 0; i < num.length; i++) {
            var name = num[i].toString();
            var html = '';
            (function reload(name) {
                getJSONData(URL + 'getSupportStatisticsColumnList.do?rnum=' + name, function(data) {
                    columnList[name] = data
                    html += '<li style="padding-bottom: 0"><span class="folder" style="color: #333">' + name + '</span>'
                    html += '<ul>';
                    if (data.zblist) {

                        $.each(data.zblist, function(index, value) {
                            values++;
                            var isChecked = '';
                            var eleChildren = '';
                            if (type && type == 'update') {
                                var tplColumnData = tplData.column;
                                for (let i = 0; i < tplColumnData.length; i++) {
                                    var element = tplColumnData[i];
                                    if (value.ID == element.zbId) {
                                        isChecked = 'checked';
                                        element.children ? eleChildren = JSON.stringify(element.children) : eleChildren = '';
                                    }
                                }
                            }

                            html += '<li>' +
                                '<span class="checkbox">' +
                                '<input id="' + value.ID + '" type="checkbox" ' + isChecked + ' value="' + value.NAME + '(' + value.ZBDM + ')" data-index="' + values + '" data-rnum="' + name + '" data-indexdm="' + value.ZBDM + '" data-indexcolumn="' + data.collist[0].COLBM + '">' +
                                '<label for="' + value.ID + '">' + value.NAME + '(' + value.ZBDM + ')</label>' +
                                '</span>' + '<b style="visibility: hidden;">' + eleChildren + '</b>' +
                                '</li>';
                        });
                    }
                    html += '</ul>'
                    html += '</li>';
                    $('#guideLine #tree1').html(html);
                    $("#tree1").treeview({
                        animated: "fast",
                        collapsed: true,
                    });
                    $('#tree1 li ul li input[type=checkbox]').change(function() {
                        treeZbNodeAdd()
                    });
                    if (type == 'update') {
                        treeZbNodeAdd()
                    }

                    function treeZbNodeAdd() {
                        flag = 0;
                        var checkBox2 = $('#tree1 li ul li input[type=checkbox]')
                        blNameArrays = []
                        for (var i = 0; i < checkBox2.length; i++) {
                            if (checkBox2[i].checked) {
                                var value1 = $(checkBox2[i]).val();
                                var index = $(checkBox2[i]).data('index');
                                var children = $(checkBox2[i]).parent().parent().find('b').text() ? JSON.parse($(checkBox2[i]).parent().parent().find('b').text()) : [];
                                var treeNode = {
                                    'zbId': $(checkBox2[i]).attr('id'),
                                    'id': $(checkBox2[i]).attr('id'),
                                    'pId': 1,
                                    'name': $.trim(value1),
                                    '': "drag:true,drop:true",
                                    'rnum': $(checkBox2[i]).data('rnum'),
                                    'indexDm': $(checkBox2[i]).data('indexdm'),
                                    'indexColumn': $(checkBox2[i]).data('indexcolumn'),
                                    'starttime': 0,
                                    'endtime': 0,
                                    'display': 'Y',
                                    'pxh': '',
                                    'columnType': 'SUM',
                                    'tjfw': ''
                                }
                                if (children.length > 0) {
                                    for (var j = 0; j < children.length; j++) {
                                        var child = children[j];
                                        child.id = child.zbId;
                                    }
                                    treeNode.children = children;
                                }
                                blNameArrays.push(treeNode);
                            }
                        }
                        var obj = {
                            'id': 1,
                            'pId': 0,
                            'name': '宾栏',
                            '': 'open:true,drag:false'
                        }
                        blNameArrays.unshift(obj);
                        if (blNameArrays.length > 0) {
                            var container = document.getElementsByClassName('table-demo')[0]
                            if (typeof zlNameArrays === 'object' && Array.isArray(zlNameArrays)) {
                                generateTable([getTreeJson(blNameArrays.slice(1), 1), getTreeJson(zlNameArrays.slice(1), 1)], container)
                            } else {
                                generateTable([getTreeJson(blNameArrays.slice(1), 1), getTreeJson(zlNameArrays.children, 1)], container)
                            }
                        }
                    }
                })
            })(name)
        }
    }

    function getSupportGroupList(tplData, type) {
        getJSONData(URL + 'getSupportGroupList.do', function(data) {
            rowList = data;
            var firstHtml = '',
                customHtml = '';
            $.each(data.normal, function(index, value) {
                var isChecked = '';
                var groupAdded = '';
                if (type && type == 'update') {
                    var tplRowData = tplData.row;
                    for (let i = 0; i < tplRowData.length; i++) {
                        var element = tplRowData[i];
                        if (value.ID == element.groupId) {
                            isChecked = 'checked';
                            groupAdded = element.groupAdded;
                        }
                    }
                }
                firstHtml += '<li>' + '<span class="checkbox">' + '<input id="' + value.ID + '" type="checkbox" ' + isChecked + ' data-index="11' + index + '" value="' + value.NAME + '" data-groupColumn="' + value.COLBM + '" data-groupType="NORMAL" data-groupAdded="'+ groupAdded +'">' + '<label for="' + value.ID + '">' + value.NAME + '</label>'
                firstHtml += '</span>'
                var strLength = value.SCHEME.split(',');
                firstHtml += '<select class="select-box" >'
                if (type && type == 'update') {
                    var tplRowData = tplData.row;
                    for (let i = 0; i < tplRowData.length; i++) {
                        var element = tplRowData[i];
                        if (value.ID == element.groupId) {
                            groupAdded = element.groupAdded;
                            for (var j = 0; j < strLength.length; j++) {
                                var index = j + 1;
                                if(index == groupAdded) {
                                    firstHtml += '<option value="' + j + '" selected>第' + (j + 1) + '层</option>'
                                } else {
                                    firstHtml += '<option value="' + j + '">第' + (j + 1) + '层</option>'
                                }
                                
                            }
                        }
                    }
                } else {
                    for (var i = 0; i < strLength.length; i++) {
                        firstHtml += '<option value="' + i + '">第' + (i + 1) + '层</option>'
                    }
                }
                firstHtml += '</select>'
                firstHtml += '</li>'
            });
            $.each(data.custom, function(index, value) {
                customHtml += '<li>' + '<span class="checkbox">' + '<input id="' + value.ID + '" type="checkbox" data-index="12' + index + '" value="' + value.NAME + '" data-groupType="CUSTOM">' + '<label for="' + value.ID + '">' + value.NAME + '</label>' + '</span>' + '</li>'
            });
            //201-1分组
            $('#201-1FenZu li ul').html(firstHtml);
            $("#201-1FenZu").treeview({
                animated: "fast"
            });
            //自定义分组
            $('#customFenZu li ul').html(customHtml);
            $("#customFenZu").treeview({
                animated: "fast"
            });

            $('.zhulanFenzu li ul li input[type=checkbox]').change(function() {
                var li = $(this).parent().parent()
                var select = li.find('select')[0]
                var cs = 1
                if (select) {
                    cs = select.selectedIndex + 1
                }
                treeGroupNodeAdd(cs)
            });

            if (type == 'update') {
                treeGroupNodeAdd(0)
            }

            function treeGroupNodeAdd(cs) {
                flag = 0;
                var checkBoxs = $('.zhulanFenzu li ul li input[type=checkbox]')
                zlNameArrays = []
                for (var i = 0; i < checkBoxs.length; i++) {
                    if (checkBoxs[i].checked) {
                        var value2 = $(checkBoxs[i]).val();
                        var index = $(checkBoxs[i]).data('index');
                        var treeNode2 = {
                            'id': $(checkBoxs[i]).attr('id'),
                            'groupId': $(checkBoxs[i]).attr('id'),
                            'pId': 2,
                            'name': $.trim(value2),
                            'cs': $(checkBoxs[i]).data('groupadded'),
                            '': "drag:true,drop:true",
                            'groupColumn': $(checkBoxs[i]).data('groupcolumn'),
                            'groupAdded': '',
                            'pxh': '',
                            'groupType': $(checkBoxs[i]).data('grouptype')
                        }
                        zlNameArrays.push(treeNode2);
                        $(checkBoxs[i]).parent('.checkbox').siblings('.select-box').show();
                        $(checkBoxs[i]).parent('.checkbox').siblings('.select-box').change(function() {
                            var cs2 = this.selectedIndex;
                            var treeId = $(this).siblings('.checkbox').find('input').attr('id');
                            for (var i = 0; i < zlNameArrays.length; i++) {
                                if (zlNameArrays[i].id == treeId) {
                                    zlNameArrays[i].cs = cs2 + 1
                                    $(this).siblings('.checkbox').find('input').attr('data-groupAdded', zlNameArrays[i].cs);
                                    break
                                }
                            }

                        })
                    } else {
                        $(checkBoxs[i]).parent('.checkbox').siblings('.select-box').hide();
                    }
                }
                var obj2 = {
                    'id': 2,
                    'pId': 0,
                    'name': '主栏',
                    '': 'open:true,drag:false'
                }
                zlNameArrays.unshift(obj2);
                if (zlNameArrays.length > 0) {
                    var container = document.getElementsByClassName('table-demo')[0]
                    if (typeof blNameArrays === 'object' && Array.isArray(blNameArrays)) {
                        generateTable([getTreeJson(blNameArrays.slice(1), 1), getTreeJson(zlNameArrays.slice(1), 1)], container)
                    } else {
                        generateTable([getTreeJson(blNameArrays.children, 1), getTreeJson(zlNameArrays.slice(1), 1)], container)
                    }
                }
            }
        });
    }
});

function showSet() {
    $("#darkdiv").show();
    $('#tj-set').show(300);
    createTree();

    originBlNameArrays = trueWayCopyObj(blNameArrays)
    originZlNameArrays = trueWayCopyObj(zlNameArrays)
}

function closeSet() {
    $("#darkdiv").hide();
    $('#tj-set').hide(200);

    blNameArrays = originBlNameArrays
    zlNameArrays = originZlNameArrays
}

//画树
function createTree() {
    var treeObj;
    var setting = {
        view: {
            addHoverDom: addHoverDom,
            removeHoverDom: removeHoverDom,
            selectedMulti: false
        },
        edit: {
            drag: {
                autoExpandTrigger: true,
                prev: dropPrev,
                inner: dropInner,
                next: dropNext
            },
            enable: true,
            editNameSelectAll: true,
            showRemoveBtn: showRemoveBtn,
            showRenameBtn: showRenameBtn
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            beforeDrag: beforeDrag,
            beforeDrop: beforeDrop,
            onDrop: onDrop
        }
    };
    if (flag == 0) {
        zNodes = (blNameArrays instanceof Array ? blNameArrays : [blNameArrays]).concat((zlNameArrays instanceof Array) ? zlNameArrays : [zlNameArrays]);
    } else {
        zNodes = saveNodes;
    }
    var zNodes2 = []
    for (var i = 0; i < zNodes.length; i++) {
        var node = trueWayCopyObj(zNodes[i])
        zNodes2.push(node)
    }
    treeObj = $.fn.zTree.init($("#treeDemo"), setting, zNodes2);
    treeObj.expandAll(true);
}

function saveTree() {
    totalSaveBtnEnable = false
    flag = 1;
    saveNodes = [];
    var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
    var nodes = treeObj.getNodes();
    var treeData = new Array();
    var blIncludeArray = new Array(),
        zlIncludeArray = new Array();

    for (var m = 0; m < nodes.length; m++) {
        var subNodes = nodes[m].children;
        if (m == 0) { //宾栏
            saveNodes.push({
                'id': nodes[0].id,
                'pId': nodes[0].pId,
                'name': nodes[0].name
            });
            saveNodes = saveNodes.concat(getSubNodes(subNodes, false))
        } else { //主栏
            saveNodes.push({
                'id': nodes[1].id,
                'pId': nodes[1].pId,
                'name': nodes[1].name
            });
            saveNodes = saveNodes.concat(getSubNodes(subNodes, true))
        }
    }
    for (var i = 0; i < saveNodes.length; i++) {
        if (saveNodes[i].children) {
            delete saveNodes[i].children
        }
    }

    function getSubNodes(nodes, iszhul) {
        var arr = []
        for (var i = 0; i < nodes.length; i++) {
            var node = nodes[i]
            arr.push(trueWayCopyObj(node))
            if (node.children && node.children.length > 0) {
                arr = arr.concat(getSubNodes(node.children, iszhul))
            }
        }
        return arr;
    }

    for (var m = 0; m < nodes.length; m++) {
        var subNodes = nodes[m].children;
        if (m == 0) { //宾栏
            blIncludeArray = getTableNodes(subNodes)
        } else { //主栏
            zlIncludeArray = getTableNodes(subNodes)
        }
    }

    function getTableNodes(nodes) {
        var arr = []
        for (var i = 0; i < nodes.length; i++) {
            var node = nodes[i]
            var tempNode = {
                'id': node.id,
                'pId': node.pId,
                'name': node.name
            }
            if (node.children && node.children.length > 0) {
                var children = []
                for (var j = 0; j < node.children.length; j++) {
                    var childNode = {
                        'id': node.children[j].id,
                        'pId': node.children[j].pId,
                        'name': node.children[j].name
                    }
                    if (node.children[j].children && node.children[j].children.length > 0) {
                        childNode.children = getTableNodes(node.children[j].children)
                    }
                    children.push(childNode)
                }
                tempNode.children = children
            }
            arr.push(tempNode)
        }
        return arr
    }
    var container = document.getElementsByClassName('table-demo')[0]
    generateTable([getTreeJson(blIncludeArray, 1), getTreeJson(zlIncludeArray, 1)], container)

    $("#darkdiv").hide();
    $('#tj-set').hide(200);
}

function getTreeJson(zData, startId) {
    var arr = [];
    for (var i = 0; i < zData.length; i++) {
        var item = trueWayCopyObj(zData[i])
        item.id = parseInt(startId + '' + (i + 1))
        item.pId = startId
        arr.push(item)
        if (item.children && item.children.length > 0) {
            var childArr = getChildArr(item.id, item.children)
            arr = arr.concat(childArr)
        }
    }
    return arr

    function getChildArr(pId, arr) {
        startIndex = 1
        var result = []
        for (var i = 0; i < arr.length; i++) {
            var item = trueWayCopyObj(arr[i])
            item.pId = pId
            item.id = parseInt(pId + '' + startIndex)
            startIndex++
            result.push(item)
            if (item.children && 　item.children.length > 0) {
                var childArr = getChildArr(item.id, item.children)
                result = result.concat(childArr)
            }
        }
        return result
    }
};